package org.kjtc.balanceController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.kjtc.balanceEntity.MeterManage;
import org.kjtc.balanceService.MeterManageService;
import org.kjtc.balanceService.MeterRecordService;
import org.kjtc.controller.BaseController;
import org.kjtc.util.Const;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BalanceRequestController extends BaseController{

	@Resource(name = "meterManageService")
	private MeterManageService meterManageService;

	@Resource(name = "meterRecordService")
	private MeterRecordService meterRecordService;

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/balance/request")
	@ResponseBody
	public Map<String, Object> balanceRequest(HttpServletRequest request, @RequestBody String requestBody){

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject json = JSONObject.fromObject(requestBody);
		JSONArray jsonArray = null;
		if (json.has("meterInfoData")) {
			logger.info("充电站同步电表信息数据meterInfoData：");
			jsonArray = Tools.getJsonArrayData(json, "meterInfoData");
			if (jsonArray != null) {
				Iterator itArray = jsonArray.iterator();
				Map<String, String> jsonMap = new HashMap<String, String>();
				List<MeterManage> meterInfoList = new ArrayList<MeterManage>();
				while (itArray.hasNext()){
					JSONObject chargingRecordJsonObject = (JSONObject) itArray.next();
					Iterator it = chargingRecordJsonObject.keys();
					while (it.hasNext()){
						String key = String.valueOf(it.next());
						String value = chargingRecordJsonObject.getString(key);
						jsonMap.put(key, value);
					}
					MeterManage meterManage = new MeterManage();
					if (jsonMap.get("chargingStationID") != null && !"null".equals(jsonMap.get("chargingStationID"))) {
						meterManage.setChargingStationID(jsonMap.get("chargingStationID"));
					}
					if (jsonMap.get("meterName") != null && !"null".equals(jsonMap.get("meterName"))) {
						meterManage.setMeterName(jsonMap.get("meterName"));
					}
					if (jsonMap.get("meterRate") != null && !"null".equals(jsonMap.get("meterRate"))) {
						meterManage.setMeterRate(jsonMap.get("meterRate"));
					}
					if (jsonMap.get("meterCode") != null && !"null".equals(jsonMap.get("meterCode"))) {
						meterManage.setMeterCode(jsonMap.get("meterCode"));
					}
					meterManage.setCreateUser("remote");
					meterManage.setUpdateUser("remote");
					meterInfoList.add(meterManage);
				}
				try {
					int length = meterInfoList.size();
					int count = 0;
					if (length > 0) {
						count = meterManageService.insertMeterInfos(meterInfoList);
						logger.info("充电站同步电表信息" + count + "条");
						if (length - count > 0) {
							logger.info("忽略充充电站同步电表信息" + (length - count) + "条");
						}
						map.put("result", "Success");
					} else {
						logger.error("充电站同步电表信息数据不存在！");
						map.put("result", "NotFound");
					}
				} catch (Exception e) {
					map.put("result", "Failed");
					logger.error("充电站同步电表信息数据异常：" + e.getMessage());
					e.printStackTrace();
				}
				meterInfoList = null;
			} else {
				logger.error("充电站同步电表信息数据不存在！");
				map.put("result", "NotFound");
			}
		} else if (json.has("checkMeterData")) {
			logger.info("充电站同步抄表数据checkMeterData：");
			jsonArray = Tools.getJsonArrayData(json, "checkMeterData");
			if (jsonArray != null) {
				try {
					meterRecordService.saveMeterRecord(jsonArray, "remote");
				} catch (Exception e) {
					map.put("result", "Failed");
					logger.error("充电站同步抄表数据异常：" + e.getMessage());
					e.printStackTrace();
				}
			} else {
				logger.error("充电站同步抄表数据不存在！");
				map.put("result", "NotFound");
			}
		} else {
			logger.error("充电站同步结算数据无法解析：" + requestBody);
			map.put("result", "Failed");
		}

		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/balance/uploadFile")
	public Object getSubStationFile(HttpServletRequest request,
			@RequestParam(value="chargingStationID", required=false) String chargingStationID,
			@RequestParam(value="type", required=false) String type) {

		Map<String, Object> map = new HashMap<String, Object>();
		Date start = new Date();
		String filePath = Const.BALANCE_PATH;
		String fileName = request.getHeader("FileName");
		logger.info("充电站" + chargingStationID + "结算文件" + fileName + "上传开始时间：" + start);
		String fileDateTime = request.getHeader("FileDateTime");
		String DateType = request.getHeader("DateType");
	    try {
	    	if (chargingStationID != null && !chargingStationID.isEmpty()) {
	    		filePath = filePath + chargingStationID + File.separator;
	    		if (type != null && !type.isEmpty()) {
		    		filePath = filePath + type + File.separator;
		    	}
		    	if (fileDateTime != null && !fileDateTime.isEmpty()) {
		    		if (!Tools.isNumeric(fileDateTime)) {
		    			logger.error("充电站结算文件时间必须是数字：'" + fileDateTime);
		    		} else {
		    			int fileLength = fileDateTime.length();
		    			if (fileLength >= 8) {
		    				if (DateType == null || DateType.isEmpty() || "DAY".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator +
			    						fileDateTime.substring(4, 6) + File.separator +
										fileDateTime.substring(6, 8) + File.separator;
			    			} else if ("MONTH".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator +
			    						fileDateTime.substring(4, 6) + File.separator;
			    			} else if ("YEAR".equals(DateType.toUpperCase())) {
			    				filePath = filePath + fileDateTime.substring(0, 4) + File.separator;
			    			}
		    			} else {
		    				logger.error("充电站结算文件时间至少是8位数字：'" + fileDateTime);
		    			}
		    		}
		    	}
		    	File file = new File(filePath);
			    if (!file.exists()) {
			    	InputStream iputstream = request.getInputStream();
			    	byte[] buffer = new byte[4*1024];
			    	int len = 0;
				    while((len = iputstream.read(buffer)) != -1){
				    	FileUtils.writeByteArrayToFile(file, buffer, 0, len, true);
				    }
				    buffer = null;
				    iputstream.close();
		 		    iputstream = null;
		 		    map.put("result", "Success");
		 		    logger.info("充电站结算文件【"+ fileName + "】上传成功:" + filePath);
			    } else {
			    	map.put("result", "Success");
			    	logger.error("充电站结算文件【"+ fileName + "】上传失败，文件已存在:" + filePath);
			    }
			    Date end = new Date();
				logger.info("充电站" + chargingStationID + "结算文件" + fileName + "上传结束时间：" + end);
	    	} else {
	    		map.put("result", "Error");
	    		logger.error("充电站ID不存在！");
	    	}
		} catch (IOException e) {
			map.put("result", "SendFailed");
			e.printStackTrace();
			logger.error("充电站结算文件【"+ fileName + "】上传异常：" + e.getMessage());
		}

		String jsonResult = JSONObject.fromObject(map).toString();
		logger.info("云平台接收充电站结算文件后返回数据：" + jsonResult);

		return jsonResult;
	}
}
